<template>
  <div class="layer-panel">
    <img src="../../assets/缩小.png" alt="" class="img-box" v-if="isLarge" title="隐藏" @click="isLarge = false">
    <img src="../../assets/放大.png" alt="" class="img-box" v-if="!isLarge" title="显示" @click="isLarge = true">
    <div class="table-panel" v-if="isLarge">
      <el-table :data="serviceList" border stripe size="mini" max-height="400">
        <el-table-column :formatter="getDataPath" label="数据地址" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="保存地址" prop="path" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column :formatter="getDataType" label="类型" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column :formatter="getDataStatus" label="状态" width="70"></el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-button @click="getAllServiceInfo" type="text" size="small">刷新</el-button>
            <el-button @click="serviceBrowse(scope.row)" type="text" size="small"
              :disabled="scope.row.section !== 1">浏览</el-button>
            <el-button @click="openLogDialog(scope.row.id)" type="text" size="small"
              v-if="modelTypes.indexOf(scope.row.type) > -1">日志</el-button>
            <el-popconfirm title="确定删除这条记录吗？" @confirm="deleteData(scope.row)">
              <el-button type="text" size="small" style="color: #f00;margin-left:10px" slot="reference">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="日志" :visible.sync="logShow" width="60%" @close="cancel" :close-on-click-modal="false"
      :modal="false">
      <div class="log-dialog">
        <div class="scroll-box">
          <div class="log-item" v-for="(item, index) in logData" :key="index">{{ item.log }}</div>
        </div>
      </div>
      <span slot="footer">
        <el-button @click="cancel">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  data () {
    return {
      logShow: false,
      serviceList: [],
      isLarge: true,
      modelPath: '',
      modelTypes: [2, 3, 4, 5, 6],
      timer: null,
      logData: []
    };
  },
  props: {
  },
  methods: {
    // 关闭日志
    cancel () {
      this.logShow = false
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    },
    // 获取日志并定位到最下方
    async getLogToBottom (id) {
      let res = await axios.get(`${window.nodeApiIp}/saveService/getLogById?id=${id}`)
      if (res.data.section == 1) {
        clearInterval(this.timer)
        this.timer = null
        this.$message.success('转换完成')
      }
      this.logData = res.data.logs
      this.$nextTick(() => {
        var container = document.querySelector('.scroll-box');
        container.scrollTop = container.scrollHeight
      })
    },
    // 打开日志弹窗
    openLogDialog (id) {
      this.logShow = true
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
      this.timer = setInterval(() => {
        this.getLogToBottom(id)
      }, 2000)
      this.getLogToBottom(id)
    },
    // 获取已经保存的服务信息
    async getAllServiceInfo () {
      let res = await axios.get(`${window.nodeApiIp}/saveService/getAllDemService`)
      this.serviceList = res.data
    },
    // 获取数据地址
    getDataPath (row) {
      let dataPath = ''
      let info = JSON.parse(row.info)
      if (row.type == 0 || row.type == 1) {
        dataPath = info.dataSet[0].files[0].path
      } else if (row.type == 2) {
        dataPath = info.osgRootDir
      } else if (row.type == 4 || row.type == 3) {
        dataPath = info.objRootDir
      } else if (row.type == 5) {
        dataPath = info.lasFileDir
      } else if (row.type == 6) {
        dataPath = info.glbInDir
      }
      return dataPath
    },
    // 获取服务类型
    getDataType (row) {
      switch (row.type) {
        case 0:
          return 'DEM切片'
        case 1:
          return 'DOM切片'
        case 2:
          return 'OSGB转3Dtiles'
        case 3:
          return '白模轻量化'
        case 4:
          return 'OBJ转3Dtiles'
        case 5:
          return 'Las转3Dtiles'
        case 6:
          return '通用模型格式转换'
      }
    },
    // 获取数据状态
    getDataStatus (row) {
      switch (row.section) {
        case 0:
          if (row.type == 0 || row.type == 1) {
            return `${parseFloat(row.scale).toFixed(2)}%`
          } else {
            return '未完成'
          }
        case 1:
          return '已完成'
      }
    },
    // 服务浏览
    serviceBrowse (row) {
      this.$parent.gridOpen = false
      this.modelPath = ''
      if (row.type == 6) {
        this.showGltf(row)
        return
      }
      this.$parent.modelPreviewShow = false
      if (row.type == 0) {
        this.updateTerrain(row)
        return
      }
      if (row.type == 1) {
        this.showDomImage(row)
        return
      }
      if (row.type == 2 || row.type == 4 || row.type == 5 || row.type == 3 || row.type == 6) {
        this.showOsgb3Dtiles(row)
      }
    },
    // 展示gltf
    async showGltf (row) {
      let res = await axios.post(`${window.nodeApiIp}/directory/getAllFilesCor`, {
        path: row.path + '\\3dtiles',
        suffix: 'gltf'
      })
      let fileList = this.getGltfPath(res.data.data)
      this.$parent.showGltf(fileList)
    },
    // 获取代理后的gltf地址
    getGltfPath (list) {
      let fileList = []
      list.forEach(i => {
        let pathArr = i.split('\\')
        let path = `${window.nodeApiIp}/`
        pathArr.forEach((item, index) => {
          if (index == 0) {
            path += item.slice(0, -1) + '/'
          } else if (item) {
            path += item + '/'
          }
        })
        path = path.slice(0, -1)
        fileList.push(path)
      })
      return fileList
    },
    // 展示OSGB转的3dtiles
    async showOsgb3Dtiles (row) {
      if (this.OSGB3Dtiles) {
        this.Global.viewer.scene.primitives.remove(this.OSGB3Dtiles);
        this.OSGB3Dtiles = null
      }
      let pathArr = row.path.split('\\')
      let path = `${window.nodeApiIp}/`
      pathArr.forEach((item, index) => {
        if (index == 0) {
          path += item.slice(0, -1) + '/'
        } else if (item) {
          path += item + '/'
        }
      })
      path = path + '3dtiles/tileset.json'
      this.modelPath = path
      this.OSGB3Dtiles = new Cesium.Cesium3DTileset({
        url: this.modelPath,
        maximumScreenSpaceError: 16,
        maximumMemoryUsage: 2000,
        useIndexDB: false
      });
      this.Global.viewer.scene.primitives.add(this.OSGB3Dtiles);
      this.OSGB3Dtiles.readyPromise.then(function (tileset) {
        //飞入模型位置
        this.Global.viewer.zoomTo(tileset, new Cesium.HeadingPitchRange(0, -0.5, 0));
      }.bind(this));
    },
    // 打开3dtiles的网格
    showGrid (boolean) {
      if (this.OSGB3Dtiles) {
        this.Global.viewer.scene.primitives.remove(this.OSGB3Dtiles);
        this.OSGB3Dtiles = null
      }
      if (this.modelPath) {
        if (boolean) {
          this.OSGB3Dtiles = new Cesium.Cesium3DTileset({
            url: this.modelPath,
            maximumScreenSpaceError: 16,
            maximumMemoryUsage: 2000,
            enableDebugWireframe: true,
            debugWireframe: true,
            useIndexDB: false
          });
          this.Global.viewer.scene.primitives.add(this.OSGB3Dtiles);
        } else {
          this.OSGB3Dtiles = new Cesium.Cesium3DTileset({
            url: this.modelPath,
            maximumScreenSpaceError: 16,
            maximumMemoryUsage: 2000,
            useIndexDB: false
          });
          this.Global.viewer.scene.primitives.add(this.OSGB3Dtiles);
        }
      } else {
        this.Global.viewer.scene.globe._surface.tileProvider._debug.wireframe = boolean;
      }
    },
    // 展示DOM影像
    async showDomImage (row) {
      let url = `${window.mapServerIp}/rasterserver/image/${row.name}/{TileMatrix}/{TileCol}/{TileRow}/getMap?tilesize=512`
      let imageLayer = new Cesium.ImageryLayer(
        new Cesium.WebMapTileServiceImageryProvider({
          show: true,
          url: url,
          format: "tiles",
          tileMatrixSetID: "c",
          subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
          tilingScheme: new Cesium.GeographicTilingScheme(),
          tileMatrixLabels: [
            "2",
            "3",
            "4",
            "5",
            "6",
            "7",
            "8",
            "9",
            "10",
            "11",
            "12",
            "13",
            "14",
            "15",
            "16",
            "17",
            "18",
            "19",
          ],
          maximumLevel: 17,
        })
      );
      this.Global.viewer.imageryLayers.add(imageLayer);
      let info = JSON.parse(row.info)
      let level = info.level
      let height = this.getZoomLevel(level - 0)
      let x = info.center.split(' ')[0].substring(6)
      let y = info.center.split(' ')[1].slice(0, -1)
      this.Global.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(x, y, height),
        orientation: {
          heading: Cesium.Math.toRadians(0),
          pitch: Cesium.Math.toRadians(-90),
          roll: Cesium.Math.toRadians(0),
        }
      })
    },
    // 调用地形
    async updateTerrain (row) {
      let terrainUrl = `${window.mapServerIp}/rasterserver/terrain/${row.name}`
      // 创建新的地形
      const terrainProvider = new Cesium.CesiumTerrainProvider({
        url: terrainUrl,
        type: "xyz",
      });
      this.Global.viewer.terrainProvider = terrainProvider;
      let info = JSON.parse(row.info)
      let dataPath = info.dataSet[0].files[0].path
      let height = await this.getBestLevel(dataPath)
      let center = JSON.parse(info.center)
      center.heigth = height
      this.Global.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(center.x, center.y, center.height),
        orientation: {
          heading: Cesium.Math.toRadians(center.heading),
          pitch: Cesium.Math.toRadians(center.pitch),
          roll: Cesium.Math.toRadians(center.roll),
        }
      })
    },
    // 获取最优层级，并换算成高度
    async getBestLevel (path) {
      let res = await axios.post(`${window.mapServerIp}/rasterserver/raster/getFitLevels`, {
        path: path,
        gridName: "degreebase256tdt"
      })
      let levels = res.data.data.levels
      let centerLevel = Math.ceil((levels[0].level + levels[levels.length - 1].level) / 2)
      let height = this.getZoomLevel(centerLevel)
      return height
    },
    // 根据level获取height
    getZoomLevel (level) {
      switch (level) {
        case 1:
          return 11900000
        case 2:
          return 11900000
        case 3:
          return 11900000
        case 4:
          return 6100000
        case 5:
          return 2600000
        case 6:
          return 1280000
        case 7:
          return 640000
        case 8:
          return 380000
        case 9:
          return 250600
        case 10:
          return 139780
        case 11:
          return 67985
        case 12:
          return 26000
        case 13:
          return 13200
        case 14:
          return 6400
        case 15:
          return 2600
        case 16:
          return 1300
        case 17:
          return 660
        case 18:
          return 300
        case 19:
          return 100
        default:
          return 100
      }
    },
    // 删除记录
    async deleteData (row) {
      let res = await axios.get(`${window.nodeApiIp}/saveService/deleteServiceInfo?id=${row.id}`)
      if (res.data.status == 200) {
        this.$message.success('删除成功')
        this.getAllServiceInfo()
      }
    }
  },
  created () { },
  mounted () {
    this.OSGB3Dtiles = null
    this.getAllServiceInfo()
    // this.$nextTick(() => {
    //   setTimeout(() => {
    //     this.OSGB3Dtiles = new Cesium.Cesium3DTileset({
    //       url: 'http://124.70.104.88:9069/tile/hb3dtiles/tileset.json',
    //       maximumScreenSpaceError: 16,
    //       maximumMemoryUsage: 2000
    //     });
    //     this.Global.viewer.scene.primitives.add(this.OSGB3Dtiles);
    //     this.OSGB3Dtiles.readyPromise.then(function (tileset) {
    //       //飞入模型位置
    //       this.Global.viewer.zoomTo(tileset, new Cesium.HeadingPitchRange(0, -0.5, 0));
    //     }.bind(this));
    //   }, 3000)
    // })
  },
  destroyed () {
    if (this.OSGB3Dtiles) {
      this.Global.viewer.scene.primitives.remove(this.OSGB3Dtiles);
      this.OSGB3Dtiles = null
    }
  }
};
</script>
<style lang="less" scoped>
.layer-panel {
  min-width: 30px;
  padding-top: 30px;
  box-sizing: border-box;
  position: absolute;
  top: 0px;
  left: 0px;
  background: rgba(0, 0, 0, 0.8);
  z-index: 11;

  .img-box {
    width: 30px;
    height: 30px;
    position: absolute;
    top: 0px;
    right: 0px;
    cursor: pointer;
  }

  .table-panel {
    width: 600px;
    height: 400px;
  }

  .log-dialog {
    width: 100%;
    height: 510px;

    .scroll-box {
      width: 100%;
      height: 100%;
      overflow-x: hidden;
      overflow-y: scroll;

      .log-item {
        margin: 10px 10px;
        line-height: 30px;
      }
    }
  }
}
</style>